package com.swiot.common.utils;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * String数组类型处理器
 * 用于处理String[]与数据库字段的转换
 * 
 * @author kingdom
 * @date 2025-09-04
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

    private static final String SEPARATOR = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null && parameter.length > 0) {
            ps.setString(i, String.join(SEPARATOR, parameter));
        } else {
            ps.setString(i, null);
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return convertToArray(value);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return convertToArray(value);
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return convertToArray(value);
    }

    /**
     * 将字符串转换为String数组
     * 
     * @param value 数据库中的字符串值
     * @return String数组
     */
    private String[] convertToArray(String value) {
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        return value.split(SEPARATOR);
    }
}
